package com.lxq.smartsign.client.ui.home;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alarmclockview.AlarmClockView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.lxq.smartsign.client.R;
import com.lxq.smartsign.client.ui.BluetoothActivity;
import com.lxq.smartsign.client.util.ClientConfig;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;


public class HomeFragment extends Fragment implements View.OnClickListener {

    private AlarmClockView clockView;
    private TextView scheduleView;

    private RequestQueue queue;

    private int forenoonHour;
    private int forenoonMinute;
    private int afternoonHour;
    private int afternoonMinute;

    private int forenoonClockInRangeHour;
    private int forenoonClockInRangeMinute;
    private int afternoonClockInRangeHour;
    private int afternoonClockInRangeMinute;

    private View rootView;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        rootView.findViewById(R.id.btn_to_scan_activity).setOnClickListener(this);
        queue= Volley.newRequestQueue(getActivity());
        rootView.findViewById(R.id.to_bluetooth_activity).setOnClickListener(this);
        clockView=rootView.findViewById(R.id.clock);
        scheduleView=rootView.findViewById(R.id.work_schedule);
        clockView.start(calendar -> {
        });
        getWorkSchedule();
        return rootView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_to_scan_activity:
                //getActivity().startActivity(new Intent(getActivity(), ScanQRActivity.class));
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, 1);
                /*String url=ClientConfig.SERVER_URL+"/socket_test";
                JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET,url,null,response -> {
                    Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
                },error -> Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show());
                queue.add(request);*/
                break;
            case R.id.to_bluetooth_activity:
                getActivity().startActivity(new Intent(getActivity(), BluetoothActivity.class));
                break;
        }
    }

    private void getWorkSchedule(){
        String url= ClientConfig.SERVER_URL+"/work_schedule";
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET,url,null,
                response -> {
                    forenoonHour=response.optInt("forenoonHour");
                    forenoonMinute=response.optInt("forenoonMinute");
                    afternoonHour=response.optInt("afternoonHour");
                    afternoonMinute=response.optInt("afternoonMinute");
                    forenoonClockInRangeHour=response.optInt("forenoonClockInRangeHour");
                    forenoonClockInRangeMinute=response.optInt("forenoonClockInRangeMinute");
                    afternoonClockInRangeHour=response.optInt("afternoonClockInRangeHour");
                    afternoonClockInRangeMinute=response.optInt("afternoonClockInRangeMinute");

                    scheduleView.setTextColor(Color.GRAY);
                    String startWork=(forenoonHour>9?forenoonHour:"0"+forenoonHour)+"："+
                            (forenoonMinute>9?forenoonMinute:"0"+forenoonMinute);
                    String endWork=(afternoonHour>9?afternoonHour:"0"+afternoonHour)+"："+
                            (afternoonMinute>9?afternoonMinute:"0"+afternoonMinute);

                    String forenoonRange=
                            (forenoonClockInRangeHour>9?forenoonClockInRangeHour:"0"+forenoonClockInRangeHour)+"："+
                                    (forenoonClockInRangeMinute>9?forenoonClockInRangeMinute:"0"+forenoonClockInRangeMinute)+"——"+
                                    (forenoonHour>9?forenoonHour:"0"+forenoonHour)+"："+
                                    (forenoonMinute>9?forenoonMinute:"0"+forenoonMinute);
                    String afternoonRange=
                            (afternoonHour>9?afternoonHour:"0"+afternoonHour)+"："+
                                    (afternoonMinute>9?afternoonMinute:"0"+afternoonMinute)+"——"+
                                    (afternoonClockInRangeHour>9?afternoonClockInRangeHour:"0"+afternoonClockInRangeHour)+"："+
                                    (afternoonClockInRangeMinute>9?afternoonClockInRangeMinute:"0"+afternoonClockInRangeMinute);

                    scheduleView.setText("上班时间："+startWork+"\n下班时间："+endWork+"\n上班打卡时间："+
                            forenoonRange+"\n下班打卡时间："+afternoonRange);
                },error -> {
            scheduleView.setText("获取上下班时间失败");
            scheduleView.setTextColor(Color.RED);
        });
        queue.add(request);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if (data==null)return;
            String result = data.getStringExtra("result");
            //Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            try {
                JSONObject qrJson=new JSONObject(result);
                String url=ClientConfig.SERVER_URL+"/by_qr_code";
                JSONObject param=new JSONObject();
                param.put("deviceId",ClientConfig.ANDROID_ID);
                param.put("monitorDeviceId",qrJson.optString("androidId"));
                param.put("password",ClientConfig.PASSWORD);
                param.put("name",ClientConfig.NAME);
                param.put("userId",ClientConfig.USER_ID);
                param.put("random",qrJson.optString("rand"));
                JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST,url,param,response ->
                        Toast.makeText(getActivity(), response.optString("msg"), Toast.LENGTH_SHORT).show(),
                        error -> Toast.makeText(getActivity(), "未知异常，打卡失败", Toast.LENGTH_SHORT).show());
                queue.add(request);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
}